package git.soulbgm.listener;

import git.soulbgm.socket.TcpClient;
import git.soulbgm.utils.ChannelUtil;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

import java.util.concurrent.TimeUnit;

/**
 * TCP通道的侦听器
 *
 * @author SoulBGM
 * @date 2021-03-29
 */
public class TcpChannelFutureListener implements ChannelFutureListener {

    private String host;
    private int port;
    private TcpConnectionSuccessListener listener;

    public TcpChannelFutureListener(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public TcpChannelFutureListener(String host, int port, TcpConnectionSuccessListener listener) {
        this(host, port);
        this.listener = listener;
    }

    @Override
    public void operationComplete(ChannelFuture future) throws Exception {
        if (future.isSuccess()) {
            TcpClient.getClient().log.info("TCP客户端连接 {}:{} 服务器成功", host, port);
            ChannelUtil.putChannelFutureListener(host, port, this);
            ChannelUtil.putChannelFuture(host, port, future);
            if (listener != null) {
                listener.operation(future);
            }
        } else {
            Runnable runnable = TcpClient.getClient().getReconnectRunnable(host, port, this);
            future.channel().eventLoop().schedule(runnable, 3L, TimeUnit.SECONDS);
        }
    }
}
